package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//编写拦截器,判断用户登录状态
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        A. 获取本次请求的URI
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        //log.info("拦截到的请求:{}", requestURI);
//        B. 判断本次请求, 是否需要登录, 才可以访问
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/imgs/**",
                "/user/sendMsg",
                "/user/login"
        };
        for (String url : urls) {
            //C. 如果不需要，则直接放行
            if (PATH_MATCHER.match(url,requestURI)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        // D-1. 判断后台登录状态，如果已登录，则直接放行
        Object employee =  request.getSession().getAttribute("employee");
        if (employee != null) {

            Long empId = (Long) request.getSession().getAttribute("employee");
            log.info("后台用户已登录,登录id为:{}",empId);

            //获取当前登录用户的id,并将id设置到当前请求访问的线程对象中
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request, response);

            //删除线程对象中的内容,释放存储空间
            BaseContext.removeCurrentId();
            return;
        }
        //D-2. 判断移动端登录状态，如果已登录，则直接放行
        Object user =  request.getSession().getAttribute("user");
        if (user != null) {

            Long userId = (Long) request.getSession().getAttribute("user");
            log.info("移动端用户已登录,用户id为:{}",userId);

            //获取当前登录用户的id,并将id设置到当前请求访问的线程对象中
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);

            //删除线程对象中的内容,释放存储空间
            BaseContext.removeCurrentId();
            return;
        }

        //E. 如果未登录, 则返回未登录结果
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
}
